package cn.slg.module.system.service.pk.utils;

import java.lang.reflect.Field;

// 反射工具类
public class ReflectUtils {
    public static String findPropertyNameByValue(Object obj, Object val) {
        Class<?> aClass = obj.getClass();
        // 拿到这个类的所有属性
        for (Field field : aClass.getDeclaredFields()) {
            field.setAccessible(true);
            try {
                if (field.get(obj) != null) {
                    if (field.get(obj).equals(val)) {
                        return field.getName();
                    }
                }
            } catch (IllegalAccessException e) {
                System.out.println(obj.getClass()+"没有该字段");
                throw new RuntimeException(e);
            }
        }
        return null;
    }


    public static Object findPropertyValueByName(Object obj, String propertyName) {
        Class<?> aClass = obj.getClass();
        Field field = null;
        try {
            field = aClass.getDeclaredField(propertyName);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        field.setAccessible(true);
        try {
            return field.get(obj);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
